#include <func.h>
#include "Request.h"
#include "Response.h"
#include "Command.h"

void upload_file(int connfd, const char* file)
{
    // 1. 构建Request对象
    Request req;
    bzero(&req, sizeof(req));

    req.type = REQ_UPLOAD;

    int fd = open(file, O_RDONLY);
    struct stat statbuf;
    fstat(fd, &statbuf);
    long fsize = statbuf.st_size;

    char command[1024];
    sprintf(command, "sha256sum %s", file);
    // 子进程执行 command, 父进程读取管道
    FILE* pipe = popen(command, "r");   
    char sha256sum[65] = {'\0'};
    fread(sha256sum, 1, 64, pipe);
    printf("sha256sum: %s\n", sha256sum);

    char path[1024] = "/peanut/dir1/a.txt";

    sprintf(req.value, "%ld %s %s", fsize, sha256sum, path);
    req.length = strlen(req.value);

    // 2. 发送 Request 
    int length = 2 * sizeof(int) + req.length;  // Request的长度
    send(connfd, &length, sizeof(int), MSG_WAITALL);
    send(connfd, &req, length, MSG_WAITALL);

    // 3. 接收 Response
    Response resp;
    recv(connfd, &length, sizeof(int), MSG_WAITALL);
    recv(connfd, &resp, length, MSG_WAITALL);

    switch (resp.status) {
    case RESP_EXIST:
        return ;
    case RESP_NOEXIST:
        break;
    }

    // 4. 发送文件内容
    char buf[4096];
    int n;
    while ((n = read(fd, buf, 4096)) > 0) {
        send(connfd, buf, n, MSG_WAITALL);
    }
    // 不要关闭连接 
}
